require "wondercap/lib/multi_configuration/task_executor"

namespace :wondercap do

  task :process_filters do
    class << self
      attr :filters
    end
    
    @filters = fetch(:filters, "").split(/,/).map do |filter_name|
      get_name_filter filter_name
    end
  end
  
  task :process_names do
    class << self
      attr :supplied_names
      attr :names, true
    end

    @supplied_names = fetch(:names, "").split(/,/)
    if (@supplied_names[0] || "").casecmp("all") == 0
      @supplied_names = []
      mc.each { |name, conf| @supplied_names << name.to_s }
    end
    @names = @supplied_names.dup
  end
  
  task :filter_names do
    process_names
    process_filters
    
    puts "names before filtering: #{names.join(",")}"
    filters.each do |filter|
      self.names = filter.call(names, self)
    end
    puts "names after filtering: #{names.join(",")}"
  end
  on :start, "wondercap:filter_names"
  
  after "wondercap:process_filters" do
    if top_task.fully_qualified_name == "wondercap:list_names"
      filters.insert 0, find_name_filter(:append_required_dependencies) if fetch(:with_deps, false)
      filters.insert 0, find_name_filter(:order_by_dependencies_filter) if fetch(:order, false)
    end
  end
  task :list_names do
    logger.info { "supplied names: #{supplied_names.join(",")}" }
    logger.info { "names after filtering: #{names.join(",")}" }
    
    ui.say(ui.list(names, :columns_across)) unless names.empty?
  end
  
  task :execute_task_on_names do
    logger.info { "supplied names: #{names.join(",")}" }
    confs = names.map { |name| mc.get_configuration(name) }
    options = {}
    options[:ignore_errors] = true if fetch(:ignore_errors, false)
    task_name = fetch :task
    begin
      Wondercap::TaskExecutor.execute(task_name, confs, options)
      trigger :task_succeeded
    rescue Wondercap::TaskExecutorError => e
      trigger :task_failed
      raise e
    end
  end
  
end